import MyIcon from '@/components/MyIcon';
import ScrollBarLayout from '@/components/ScrollBarLayout';
import { TypographyTitle } from '@/components/Typography';
import { requestFunCompon, toTree } from '@/utils';
import {
  AutoComplete,
  Card,
  Col,
  Descriptions,
  Drawer,
  Empty,
  Input,
  Menu,
  message,
  Radio,
  Row,
  Spin,
} from 'antd';
import { ChangeEvent, useContext, useEffect, useMemo, useState } from 'react';
import { useRequest } from 'umi';
import { RouleManageContext } from '../hooks';
import { IRoleDetailDrawer } from '../type';
const DesItem = Descriptions.Item;
import { SearchOutlined } from '@ant-design/icons';
import cls from 'classnames';
import _ from 'lodash';

export const RoleDetailDrawer: React.FC<IRoleDetailDrawer> = ({
  visible,
  onRowDetail,
  onCloceDrawer,
}) => {
  const { prefixCls, rouleDispatch, roleDetailRightValue } = useContext(
    RouleManageContext,
  );

  // 保存当前按钮选中的是数据范围还是功能操作
  const [tabBtnType, setTabBtnType] = useState<string>('secopeBtn');
  const [onMenuTreeKey, setOnMenuTreeKey] = useState<string[]>([]); //选中的菜单id
  const [onMenuDefauKey, setOnMenuDefauKey] = useState<string[]>([]); //选中的菜单id

  /** 点击菜单修改 */
  const saveMenuTreeKey = (onKeyObj: any, isDefault: boolean) => {
    if (isDefault) {
      setOnMenuTreeKey([onKeyObj?.id]);
      setOnMenuDefauKey([onKeyObj?.pID]);
    } else {
      setOnMenuTreeKey(onKeyObj?.selectedKeys);
    }
  };

  // 保存详情信息
  const [detailInfoRole, setDetailInfoRole] = useState<any>(null);

  const [roleMenuRows, setRoleMenuRows] = useState<any[]>([]); // 保存权限菜单信息

  // 保存数据范围
  const [secopeObj, setSecopeObj] = useState<any>({});
  const [handleObj, setHandleObj] = useState<any>({});
  const saveMenuIds = (secopeRow: any, handleRow: any) => {
    setSecopeObj(secopeRow);
    setHandleObj(handleRow);
  };

  // 获取详情信息
  const getDetailInfo = useRequest(
    (paramsObj: any) => {
      let url = `/roleController/getRoleByID/${paramsObj?.id}`;
      return requestFunCompon('GET', url);
    },
    {
      manual: true,
      onSuccess: (res: any) => {
        if (res && res?.msgFlag) {
          message?.success(res?.msg);
          handleInfoSplit(res?.obj?.paramObject);
          setDetailInfoRole(res?.obj);
        }
      },
    },
  );

  // 处理右侧数据
  const handleInfoSplit = (roleRows: any) => {
    let menuTree = roleRows?.menu?.length > 0 ? toTree(roleRows?.menu) : [];
    let scopeTree = roleRows?.scope?.length > 0 ? toTree(roleRows?.scope) : [];
    let handleTree =
      roleRows?.handle?.length > 0 ? toTree(roleRows?.handle) : [];

    let menuIDS: string[] = [];

    roleRows?.menu?.forEach((item: any) => {
      // if (item?.textType == 1) {
      menuIDS?.push(item?.id);
      // }
    });

    //处理默认选择第一个菜单数据
    if (menuTree?.length > 0) {
      saveMenuTreeKey(menuTree?.[0], true);
    }

    setRoleMenuRows(menuTree);
    if (menuIDS && menuIDS?.length > 0) {
      const secopeData = handleScope(menuIDS, scopeTree);
      const handleData = handleScope(menuIDS, handleTree);
      saveMenuIds(secopeData, handleData);
    }
  };

  // 处理数据范围
  const handleScope = (menuList: any[], dataObj: any) => {
    let paramsData: Record<string, any> = {};
    let childObj: any = [];
    menuList?.forEach((item: any) => {
      childObj = dataObj?.filter((itemChild: any) => {
        return item == itemChild?.pID;
      });
      paramsData[item] = childObj;
    });
    return paramsData;
  };

  useEffect(() => {
    if (visible) {
      getDetailInfo?.run(onRowDetail);
    }
    return () => {
      setDetailInfoRole(null);
      setTabBtnType('secopeBtn');
      rouleDispatch({
        type: 'role-roleDetailRightValue',
        payload: '',
      });
    };
  }, [visible]);

  // 处理 menu菜单
  // const handleMenu = (list: any[]) => {
  //   return list?.map((item: any, index: number) => {
  //     const name = item?.name ?? item?.text;
  //     const nameLength = name?.length;
  //     const select = name?.search(detailMenuLeftValue);
  //     const searchLength = detailMenuLeftValue?.length;
  //     const afterStr = name?.slice(0, select);
  //     const selectStr = detailMenuLeftValue;
  //     const beforeStr = name?.slice(select + searchLength, nameLength);
  //     const titleTree =
  //       select > -1 && selectStr ? (
  //         <>
  //           {afterStr}
  //           <span style={{ color: '#f50' }}>{selectStr}</span>
  //           {beforeStr}
  //         </>
  //       ) : (
  //         <>{item?.name ?? item?.text ?? '--'}</>
  //       );

  //     if (item?.resourceType == 1 || item?.textType == 1) {
  //       return (
  //         <Menu.Item
  //           key={item?.id}
  //           id={item?.id + 'left'}
  //           icon={<MyIcon type={item?.icon} style={{ marginRight: 5 }} />}
  //           itemRef={item}
  //         >
  //           {titleTree}
  //         </Menu.Item>
  //       );
  //     }
  //     if (item?.resourceType == 0 || item?.textType == 0) {
  //       return (
  //         <Menu.SubMenu
  //           key={item?.id}
  //           title={titleTree}
  //           icon={<MyIcon type={item?.icon} style={{ marginRight: 5 }} />}
  //           onTitleClick={(e) => {
  //             let subMenuObj: any = {
  //               // item: item,
  //               selectedKeys: [e?.key],
  //             };
  //             menuClick(subMenuObj);
  //           }}
  //         >
  //           {item?.children &&
  //             item?.children?.length > 0 &&
  //             handleMenu(item?.children)}
  //         </Menu.SubMenu>
  //       );
  //     }
  //   });
  // };

  // 处理右侧渲染数据
  const handleRightData = useMemo(() => {
    let onMenuId = onMenuTreeKey?.length > 0 ? onMenuTreeKey?.toString() : null;
    let renderRightList: any[] = [];

    if (onMenuId) {
      if (tabBtnType == 'secopeBtn') {
        renderRightList = secopeObj?.[onMenuId];
      } else if (tabBtnType == 'handleBtn') {
        renderRightList = handleObj?.[onMenuId];
      }
    } else {
      renderRightList = [];
    }
    return renderRightList;
  }, [secopeObj, handleObj, tabBtnType, onMenuTreeKey]);

  // 搜索下拉菜单
  const autoOptionRight = useMemo(() => {
    let option: Record<string, any>[] = [];
    const tileTreeData = (data: Record<string, any>[]) => {
      data?.forEach((item) => {
        if ((item?.text || item?.name)?.includes(roleDetailRightValue)) {
          // const name = item?.text || item?.name;
          // const nameLength = name?.length;
          // const select = name?.search(roleDetailRightValue);
          // const searchLength = roleDetailRightValue?.length;
          // const afterStr = name?.slice(0, select);
          // const selectStr = roleDetailRightValue;
          // const beforeStr = name?.slice(select + searchLength, nameLength);
          option.push({
            value: item?.text || item?.name,
            key: item?.id,
            // label: (
            //   <div>
            //     <span>{afterStr}</span>
            //     <span style={{ color: '#f50' }}>{selectStr}</span>
            //     <span>{beforeStr}</span>
            //   </div>
            // ),
          });
        }
      });
    };
    tileTreeData(handleRightData);
    return option;
  }, [handleRightData, roleDetailRightValue, tabBtnType]);

  // 点击搜索
  const onAutoSelect = (value: string, option: any) => {
    const promise = new Promise((resolve) => {
      const optionId = option?.key;
      rouleDispatch({
        type: 'role-roleDetailRightValue',
        payload: value,
      });

      setTimeout(() => {
        scrollToAnchor(optionId);
      }, 1000);

      resolve(optionId);
    });
    promise.then((res: any) => {
      if (res) {
      }
    });
  };

  // 滚动定位
  const scrollToAnchor = (id: string) => {
    let anchorElement = document.getElementById(id + 'roleDetaRightCard');
    if (id) {
      anchorElement?.scrollIntoView({ behavior: 'smooth', inline: 'start' });
    }
  };
  // 搜索框改变
  const onInputChange = (e: ChangeEvent<HTMLInputElement>) => {
    rouleDispatch({
      type: 'role-roleDetailRightValue',
      payload: e?.target?.value,
    });
  };

  // 处理搜索变色
  const searchChangeStyle = (itemObj: Record<string, any>) => {
    const name = itemObj?.name || itemObj?.text;
    const nameLength = name?.length;
    const select = name?.search(roleDetailRightValue);
    const searchLength = roleDetailRightValue?.length;
    const afterStr = name?.slice(0, select);
    const selectStr = roleDetailRightValue;
    const beforeStr = name?.slice(select + searchLength, nameLength);
    const title =
      select > -1 && selectStr ? (
        <div id={itemObj?.id + 'roleDetaRightCard'}>
          <MyIcon type={itemObj?.icon} />
          &nbsp;
          {afterStr}
          <span style={{ color: '#f50' }}>{selectStr}</span>
          {beforeStr}
        </div>
      ) : (
        <div id={itemObj?.id + 'roleDetaRightCard'}>
          <MyIcon type={itemObj?.icon} />
          &nbsp;
          {itemObj?.name || itemObj?.text}
        </div>
      );
    return title;
  };

  /** 角色授权 详情 Menu 菜单  V4.24.8  */
  const roleDetailMenuItems = useMemo(() => {
    let menuList: any[] = _.cloneDeep(roleMenuRows);
    const loopMenuTree = (treeList: Record<string, any>[]) => {
      treeList?.forEach((item: any, index: number) => {
        treeList[index] = {
          key: item?.id,
          label: (
            <span
              style={{ width: '100%', display: 'inline-block' }}
              onClick={() => {
                if (
                  (item?.resourceType == 0 || item?.textType == 0) &&
                  !onMenuDefauKey?.includes(item?.id)
                ) {
                  let subMenuObj: any = {
                    selectedKeys: [item?.id],
                  };
                  saveMenuTreeKey(subMenuObj, false);
                }
              }}
            >
              <MyIcon type={item?.icon} style={{ marginRight: 5 }} />
              &nbsp;
              {item?.name ?? item?.text}
            </span>
          ),
          itemRef: { ...item },
          children:
            item?.children && item?.children?.length > 0
              ? loopMenuTree(item?.children)
              : null,
        };
      });
      return treeList;
    };
    const newMenuList: any[] = loopMenuTree(menuList);
    return newMenuList;
  }, [roleMenuRows, onMenuTreeKey, onMenuDefauKey, tabBtnType]);

  return (
    <>
      <Drawer
        open={visible}
        onClose={() => {
          onCloceDrawer(false);
        }}
        title={<div>角色详情</div>}
        style={{ position: 'absolute' }}
        placement="right"
        getContainer={false}
        width={document.body.clientWidth * 0.55}
        headerStyle={{
          padding: '.5rem',
        }}
        bodyStyle={{
          padding: '10px 5px',
        }}
        closable={false}
        destroyOnClose={true}
      >
        <ScrollBarLayout>
          <div style={{ display: visible ? 'block' : 'none', height: '100%' }}>
            {getDetailInfo?.loading ? (
              <>
                <Spin spinning={getDetailInfo?.loading}>
                  <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />
                </Spin>
              </>
            ) : (
              <>
                <div style={{ padding: '0px 10px 10px 10px', height: '100%' }}>
                  {detailInfoRole && detailInfoRole?.id ? (
                    <>
                      <div style={{ padding: '0px 0px 10px 0px' }}>
                        <TypographyTitle
                          level={4}
                          style={{
                            margin: 0,
                          }}
                        >
                          角色信息
                        </TypographyTitle>
                      </div>
                      <div className={prefixCls + 'detailRoleInfo'}>
                        <Descriptions bordered={true} size="small" column={4}>
                          <DesItem
                            span={4}
                            label={
                              <span>
                                <MyIcon type="icon-renliziyuan" />
                                &nbsp;&nbsp;角色名称
                              </span>
                            }
                          >
                            {(detailInfoRole && detailInfoRole.name) || '--'}
                          </DesItem>
                          <DesItem
                            span={4}
                            label={
                              <span>
                                <MyIcon type="icon-wenbenyu" />
                                &nbsp;&nbsp;角色描述
                              </span>
                            }
                          >
                            {detailInfoRole && detailInfoRole?.describeInfo
                              ? detailInfoRole?.describeInfo
                              : '--'}
                          </DesItem>
                          <DesItem
                            span={4}
                            label={
                              <span>
                                <MyIcon type="icon-renliziyuan" />
                                &nbsp;&nbsp;上级角色
                              </span>
                            }
                          >
                            {detailInfoRole && detailInfoRole?.pName
                              ? detailInfoRole?.pName
                              : '--'}
                          </DesItem>
                          <DesItem
                            span={2}
                            label={
                              <span>
                                <MyIcon type="paixu" />
                                &nbsp;&nbsp;排序
                              </span>
                            }
                          >
                            <span>
                              {detailInfoRole && detailInfoRole?.seq
                                ? detailInfoRole?.seq
                                : '0'}
                            </span>
                          </DesItem>
                          <DesItem
                            span={2}
                            label={
                              <span>
                                <MyIcon type="zhuangtai" />
                                &nbsp;&nbsp;角色状态
                              </span>
                            }
                          >
                            <span
                              style={{
                                color:
                                  detailInfoRole?.isOpen == 1
                                    ? '#52c41a'
                                    : '#f00',
                              }}
                            >
                              {detailInfoRole && detailInfoRole.isOpen == 1
                                ? '启用'
                                : '禁用' || '--'}
                            </span>
                          </DesItem>
                          <DesItem
                            span={4}
                            label={
                              <span>
                                <MyIcon type="icon-beizhu" />
                                &nbsp;&nbsp;备注
                              </span>
                            }
                          >
                            {(detailInfoRole && detailInfoRole?.remark) || '--'}
                          </DesItem>
                        </Descriptions>
                      </div>
                      <div>
                        <div style={{ padding: '15px 0px 10px 0px' }}>
                          <TypographyTitle
                            level={4}
                            style={{
                              margin: 0,
                            }}
                          >
                            权限信息
                          </TypographyTitle>
                        </div>
                        {roleMenuRows && roleMenuRows?.length > 0 ? (
                          <div
                            style={{ height: document.body.clientHeight * 0.5 }}
                            className={prefixCls + 'roleDetailAll'}
                          >
                            <Radio.Group
                              options={[
                                {
                                  value: 'secopeBtn',
                                  label: '数据范围',
                                },
                                {
                                  value: 'handleBtn',
                                  label: '功能操作',
                                },
                              ]}
                              optionType={'button'}
                              buttonStyle="solid"
                              value={tabBtnType}
                              onChange={(e: any) => {
                                setTabBtnType(e?.target?.value);
                                rouleDispatch({
                                  type: 'role-roleDetailRightValue',
                                  payload: '',
                                });
                              }}
                            />
                            {/* <ScrollBarLayout> */}
                            <Row style={{ height: '100%' }}>
                              <Col
                                span={8}
                                className={
                                  prefixCls + 'roleDetailAll-roleColLeftBorder'
                                }
                                style={{ height: '100%' }}
                              >
                                <ScrollBarLayout>
                                  <Menu
                                    mode="inline"
                                    theme="light"
                                    selectedKeys={onMenuTreeKey} //选中的 菜单
                                    openKeys={onMenuDefauKey} //展开的 目录
                                    onSelect={(itemObj: any) => {
                                      const { itemRef } = itemObj?.item?.props;
                                      let menuObj: any = {
                                        selectedKeys: [itemRef?.id],
                                      };
                                      saveMenuTreeKey(menuObj, false);
                                    }}
                                    items={roleDetailMenuItems}
                                    onOpenChange={(openKeys: string[]) => {
                                      setOnMenuDefauKey(openKeys);
                                    }}
                                  >
                                    {/* {handleMenu(roleMenuRows)} */}
                                  </Menu>
                                </ScrollBarLayout>
                              </Col>
                              <Col
                                span={16}
                                className={
                                  prefixCls + 'roleDetailAll-roleDetailCol'
                                }
                                style={{ height: '100%' }}
                              >
                                {handleRightData?.length > 0 ? (
                                  <>
                                    <div
                                      style={{
                                        width: '100%',
                                        display: 'flex',
                                        justifyContent: 'flex-end',
                                        marginBottom: 5,
                                      }}
                                    >
                                      <AutoComplete
                                        style={{ width: '50%' }}
                                        options={autoOptionRight}
                                        notFoundContent={
                                          <Empty
                                            image={Empty.PRESENTED_IMAGE_SIMPLE}
                                          />
                                        }
                                        onSelect={onAutoSelect}
                                      >
                                        <Input
                                          suffix={<SearchOutlined />}
                                          onChange={onInputChange}
                                          placeholder="请按名称搜索"
                                          allowClear={true}
                                        />
                                      </AutoComplete>
                                    </div>
                                    <ScrollBarLayout
                                      style={{
                                        height: '90%',
                                        padding: '10px 5px',
                                      }}
                                    >
                                      <div
                                        className={cls(
                                          prefixCls + 'rightCardAuth',
                                        )}
                                      >
                                        {handleRightData?.map((item: any) => {
                                          return (
                                            <div
                                              key={item?.id + 'rightCardTitle'}
                                            >
                                              <Card
                                                bordered
                                                title={searchChangeStyle(item)}
                                              >
                                                <ScrollBarLayout
                                                  style={{
                                                    padding: '5px 10px',
                                                    height:
                                                      document.body
                                                        .clientHeight * 0.2,
                                                  }}
                                                >
                                                  {item?.children?.length >
                                                  0 ? (
                                                    <div
                                                      className={
                                                        prefixCls +
                                                        'rightCardAuth-detailCard'
                                                      }
                                                    >
                                                      {item?.children?.map(
                                                        (itemChildren: any) => {
                                                          return (
                                                            <div
                                                              id={
                                                                itemChildren?.id
                                                              }
                                                              key={
                                                                itemChildren?.id
                                                              }
                                                              // style={{ padding: '5px 10px' }}
                                                              className={
                                                                prefixCls +
                                                                'rightCardAuth-roleDetailCardChildBorder'
                                                              }
                                                            >
                                                              <span>
                                                                <MyIcon
                                                                  type={
                                                                    itemChildren?.icon
                                                                  }
                                                                  style={{
                                                                    marginRight:
                                                                      '5px',
                                                                  }}
                                                                />
                                                                {itemChildren?.name ||
                                                                  itemChildren?.text}
                                                              </span>
                                                            </div>
                                                          );
                                                        },
                                                      )}
                                                    </div>
                                                  ) : (
                                                    <Empty
                                                      image={
                                                        Empty.PRESENTED_IMAGE_SIMPLE
                                                      }
                                                    />
                                                  )}
                                                </ScrollBarLayout>
                                              </Card>
                                            </div>
                                          );
                                        })}
                                      </div>
                                    </ScrollBarLayout>
                                  </>
                                ) : (
                                  <>
                                    <Empty
                                      image={Empty.PRESENTED_IMAGE_SIMPLE}
                                    />
                                  </>
                                )}
                              </Col>
                            </Row>
                            {/* </ScrollBarLayout> */}
                          </div>
                        ) : (
                          <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />
                        )}
                      </div>
                    </>
                  ) : (
                    <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />
                  )}
                </div>
              </>
            )}
          </div>
        </ScrollBarLayout>
      </Drawer>
    </>
  );
};
